import React, { useState, useEffect } from 'react';
import { 
  Row, 
  Col, 
  Card, 
  Button, 
  InputNumber, 
  message, 
  Spin, 
  Typography, 
  Divider,
  Tag,
  Space,
  Image,
  Breadcrumb
} from 'antd';
import { 
  ShoppingCartOutlined, 
  ArrowLeftOutlined,
  HomeOutlined,
  BookOutlined
} from '@ant-design/icons';
import { useParams, useNavigate } from 'react-router-dom';
import { bookApi, cartApi, authApi } from '../../api';

const { Title, Paragraph, Text } = Typography;

const BookDetail = () => {
  const [loading, setLoading] = useState(true);
  const [book, setBook] = useState(null);
  const [quantity, setQuantity] = useState(1);
  const [addingToCart, setAddingToCart] = useState(false);
  
  const { id } = useParams();
  const navigate = useNavigate();

  // 获取书籍详情
  const fetchBookDetail = async () => {
    setLoading(true);
    try {
      const response = await bookApi.getBookById(id);
      if (response.success) {
        setBook(response.data);
      } else {
        message.error(response.message || '获取书籍详情失败');
        navigate('/books');
      }
    } catch (error) {
      console.error('获取书籍详情错误:', error);
      message.error('获取书籍详情失败');
      navigate('/books');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (id) {
      fetchBookDetail();
    }
  }, [id]);

  // 添加到购物车
  const addToCart = async () => {
    if (!authApi.isAuthenticated()) {
      message.warning('请先登录');
      navigate('/login');
      return;
    }

    if (quantity > book.stock) {
      message.error('库存不足');
      return;
    }

    setAddingToCart(true);
    try {
      const response = await cartApi.addToCart(book.id, quantity);
      if (response.success) {
        message.success(`已添加 ${quantity} 本到购物车`);
        setQuantity(1);
      } else {
        message.error(response.message || '添加到购物车失败');
      }
    } catch (error) {
      console.error('添加到购物车错误:', error);
      message.error('添加到购物车失败');
    } finally {
      setAddingToCart(false);
    }
  };

  if (loading) {
    return (
      <div style={{ 
        display: 'flex', 
        justifyContent: 'center', 
        alignItems: 'center', 
        minHeight: '400px' 
      }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!book) {
    return (
      <div style={{ textAlign: 'center', padding: '50px 0' }}>
        <Text type="secondary">书籍不存在</Text>
      </div>
    );
  }

  return (
    <div>
      {/* 面包屑导航 */}
      <Breadcrumb style={{ marginBottom: 16 }}>
        <Breadcrumb.Item>
          <HomeOutlined />
          <span style={{ marginLeft: 4 }}>首页</span>
        </Breadcrumb.Item>
        <Breadcrumb.Item>
          <BookOutlined />
          <span style={{ marginLeft: 4 }}>全部书籍</span>
        </Breadcrumb.Item>
        <Breadcrumb.Item>{book.name}</Breadcrumb.Item>
      </Breadcrumb>

      {/* 返回按钮 */}
      <Button 
        icon={<ArrowLeftOutlined />} 
        onClick={() => navigate('/books')}
        style={{ marginBottom: 16 }}
      >
        返回书籍列表
      </Button>

      <Row gutter={32}>
        {/* 书籍封面 */}
        <Col xs={24} md={10}>
          <Card>
            <div style={{ 
              display: 'flex', 
              justifyContent: 'center',
              alignItems: 'center',
              minHeight: '400px',
              background: '#f5f5f5'
            }}>
              <Image
                src={book.cover}
                alt={book.name}
                style={{ 
                  maxWidth: '100%',
                  maxHeight: '400px',
                  objectFit: 'contain'
                }}
                fallback=""
              />
            </div>
          </Card>
        </Col>

        {/* 书籍信息 */}
        <Col xs={24} md={14}>
          <div>
            <Title level={2}>{book.name}</Title>
            
            <Space direction="vertical" size="middle" style={{ width: '100%' }}>
              <div>
                <Text strong>作者：</Text>
                <Text>{book.author}</Text>
              </div>
              
              <div>
                <Text strong>出版社：</Text>
                <Text>{book.publisher}</Text>
              </div>
              
              <div>
                <Text strong>ISBN：</Text>
                <Text>{book.isbn}</Text>
              </div>
              
              <div>
                <Text strong>库存：</Text>
                <Tag color={book.stock > 10 ? 'green' : book.stock > 0 ? 'orange' : 'red'}>
                  {book.stock > 0 ? `${book.stock} 本` : '缺货'}
                </Tag>
              </div>
              
              <div>
                <Text strong style={{ fontSize: '18px' }}>价格：</Text>
                <Text style={{ 
                  color: '#ff4d4f', 
                  fontSize: '24px', 
                  fontWeight: 'bold' 
                }}>
                  ¥{book.price?.toFixed(2)}
                </Text>
              </div>
              
              <Divider />
              
              {/* 购买操作 */}
              <div>
                <Space size="large" align="center">
                  <div>
                    <Text strong>数量：</Text>
                    <InputNumber
                      min={1}
                      max={book.stock}
                      value={quantity}
                      onChange={setQuantity}
                      style={{ marginLeft: 8 }}
                    />
                  </div>
                  
                  <Button
                    type="primary"
                    size="large"
                    icon={<ShoppingCartOutlined />}
                    loading={addingToCart}
                    disabled={book.stock === 0}
                    onClick={addToCart}
                  >
                    加入购物车
                  </Button>
                </Space>
              </div>
            </Space>
          </div>
        </Col>
      </Row>

      {/* 书籍描述 */}
      {book.description && (
        <Card title="书籍简介" style={{ marginTop: 24 }}>
          <Paragraph>
            {book.description}
          </Paragraph>
        </Card>
      )}
    </div>
  );
};

export default BookDetail; 